package com.wangwenjun.concurrency.chapter6;

/**
 * @author
 * @Title: ThreadService
 * @Description:
 * @date 2022/5/21 7:51 下午
 */
public class ThreadService {

    private Thread executeThread;

    private boolean isFinish = false;

    public void execute(Runnable runnable){
        executeThread = new Thread(){
            @Override
            public void run() {
                Thread daemonThread = new Thread(runnable);
                daemonThread.setDaemon(true); //实际执行外部业务的是守护线程
                daemonThread.start();

                try {
                    daemonThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                isFinish = true;

            }
        };
        executeThread.start();
    }

    public void shutdown(long time){
        long now = System.currentTimeMillis();
        while(!isFinish){
            if(System.currentTimeMillis() - now < time){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                executeThread.interrupt();
            }
        }
        isFinish = false;
    }
}
